package com.hifar.plugins;

import com.deepoove.poi.data.TextRenderData;
import com.deepoove.poi.policy.AbstractRenderPolicy;
import com.deepoove.poi.policy.TextRenderPolicy;
import com.deepoove.poi.render.RenderContext;
import com.tssk.kylx.fw.utils.lang.DateUtils;
import com.tssk.kylx.fw.utils.lang.NumberUtils;
import com.tssk.kylx.fw.utils.lang.StringUtils;
import org.apache.poi.xwpf.usermodel.XWPFRun;

import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description: 日期渲染插件
 * @Author zhuWeiWei
 * @Date 2022/12/7 17:38
 */
public class TimeRenderPolicy extends AbstractRenderPolicy<Object> {
    /**
     * 日期格式
     */
    private String datePattern = "yyyy-MM-dd HH:mm:ss";
    /**
     * 为空时展示的值,isNullClear 为true时生效
     */
    private String defaultVal = "";
    /**
     * 为空时是否删除标签
     */
    private boolean isNullClear = false;

    /**
     * 判断是否是时间戳
     */
    private static Pattern NUM_PATTERN = Pattern.compile("\\d{13}");

    @Override
    public void doRender(RenderContext<Object> context) {
        String data = wrapper(context.getData());
        XWPFRun run = context.getRun();
        if (StringUtils.isNotBlank(data) || isNullClear) {
            TextRenderPolicy.Helper.renderTextRun(run, new TextRenderData(data));
        }
    }

    @Override
    protected void afterRender(RenderContext<Object> context) {
        String data = wrapper(context.getData());
        if (StringUtils.isBlank(data) && this.isNullClear) {
            this.clearPlaceholder(context, false);
        }
    }


    private String wrapper(Object data) {
        String timeData = "";
        if (data instanceof Date) {
            Date date = (Date) data;
            timeData = DateUtils.formatTime(date, datePattern);
            return timeData;
        }
        timeData = StringUtils.trimNull(data);
        if (this.isNullClear && StringUtils.isEmptyZero(timeData)) {
            return this.defaultVal;
        }
        if (StringUtils.isNotEmpty(timeData)) {
            Matcher matcher = NUM_PATTERN.matcher(timeData);
            if (matcher.matches()) {
                long time = NumberUtils.parseLong(data);
                timeData = DateUtils.formatTime(new Date(time), datePattern);
            }
        }
        return timeData;
    }

    public TimeRenderPolicy() {

    }

    public TimeRenderPolicy(String pattern) {
        this.datePattern = pattern;
        this.isNullClear = true;
    }

    public TimeRenderPolicy(String pattern, Boolean isNullClear) {
        this.datePattern = pattern;
        this.isNullClear = isNullClear;
    }

    public TimeRenderPolicy(String pattern, String defaultVal) {
        this.datePattern = pattern;
        this.defaultVal = defaultVal;
        this.isNullClear = true;
    }

}
